package luz.javaproxy.init;


import java.io.IOException;
import java.io.InterruptedIOException;

import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import luz.javaproxy.config.ConfigMgr;
import luz.javaproxy.gui.MainWindow;
import luz.javaproxy.plugin.PluginMgr;
import luz.javaproxy.proxy.Proxy;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class Init {
	private static final Log log = LogFactory.getLog(Init.class);
	private enum Mode{GUI, CONSOLE}
	
    public static void main(String[] args) {
    	
    	//Collect Parameters
    	Mode mode = null;
    	switch (args.length){
	    	case 0: 
	    		mode=Mode.GUI;
	    		break;
	    	case 1:
	    		if (args[0].equalsIgnoreCase("-"+Mode.GUI.name()))
	    			mode=Mode.GUI;
	    		else if (args[0].equalsIgnoreCase("-"+Mode.CONSOLE.name()))
	    			mode=Mode.CONSOLE;
	    		break;
	    	default:
	    		mode=Mode.GUI;
    	}
    		
    	//Init application    	
		final ConfigMgr cMgr = new ConfigMgr();
		cMgr.loadConfig();
		
    	if (mode==Mode.GUI){
    		//////////////////////////////////////////////////////
    		//						GUI							//
    		//////////////////////////////////////////////////////
    		try {
				UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			} catch (ClassNotFoundException e)          { log.warn("getSystemLookAndFeelClassName", e);
			} catch (InstantiationException e)          { log.warn("getSystemLookAndFeelClassName", e);
			} catch (IllegalAccessException e)          { log.warn("getSystemLookAndFeelClassName", e);
			} catch (UnsupportedLookAndFeelException e) { log.warn("getSystemLookAndFeelClassName", e);
			}
			final PluginMgr pMgr = PluginMgr.getInstance();
			pMgr.init(cMgr);
    		
    		SwingUtilities.invokeLater(new Runnable() {
    			public void run() {
    				MainWindow inst = new MainWindow(pMgr, cMgr);
    				inst.setLocationRelativeTo(null);
    				inst.setVisible(true);
    			}
    		});

    	} else if (mode==Mode.CONSOLE){
    		//////////////////////////////////////////////////////
    		//						CONSOLE						//
    		//////////////////////////////////////////////////////
    		final PluginMgr pMgr = PluginMgr.getInstance();
    		String address = cMgr.getProxyConfig().getAddress();
    		int port = cMgr.getProxyConfig().getPort();
    		
        	final Proxy proxy = new Proxy(address, port, pMgr);
        	pMgr.init(cMgr);
	        try {
	            proxy.run();
	        } catch (InterruptedIOException ex) {
	            log.error("Proxy Interrupted");
	        } catch (IOException e) {
	        	log.error("Proxy I/O error: " + e.getMessage());
	        }
	    	cMgr.saveConfig();
			//TODO avoid sys exit
			System.exit(0);
    	} else {
    		System.out.println("valid arguments are: -console -gui");
    	}
    	

    }
}